package com.peng.leetcode.trie;

import java.util.HashMap;
import java.util.Map;

/**
 * TrieTree2
 * <p>
 * 208. 实现 Trie (前缀树)
 *
 * @author: lupeng6
 * @create: 2021/4/14 11:18
 */
public class TrieTree2 {


    public static void main(String[] args) {
        String[] words = {"Trie", "insert", "search", "search", "startsWith", "insert", "search", "apple"};
        TrieTree2 trie = new TrieTree2();
        for (String word : words) {
            trie.insert(word);
        }

        System.out.println(trie.search("apple"));
        System.out.println(trie.search("app"));
        System.out.println(trie.startsWith("app"));
    }


    static class Node {
        boolean end = false;
        Map<Character, Node> links = new HashMap<>();
    }

    private Node root;

    /**
     * Initialize your data structure here.
     */
    public TrieTree2() {
        this.root = new Node();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        int len = word.length();
        Node curr = root;
        for (int i = 0; i < len; i++) {
            char c = word.charAt(i);
            curr.links.putIfAbsent(c, new Node());
            curr = curr.links.get(c);
        }
        curr.end = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        Node curr = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            Node node = curr.links.get(c);
            if (node == null) {
                return false;
            }
            curr = node;
        }
        return curr.end;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        Node curr = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            Node node = curr.links.get(c);
            if (node == null) {
                return false;
            }
            curr = node;
        }
        return true;
    }


}
